package d512a.TAKO;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.google.zxing.client.android.CaptureActivity;

import d512a.TAKO.helpers.ColorHelper;
import d512a.TAKO.helpers.DataBaseHelper;
import d512a.TAKO.helpers.DateHelper;

public class BasketActivity extends Activity {

    private final CharSequence[] selections = { "Vis info", "Fjern" };

    private DataBaseHelper db;
    private String date;
    private Cursor cursor;
    private AlertDialog alert;
    private ArrayList<String> items = new ArrayList<String>();
    private View myView;
    private ListView list;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.basket);

        db = new DataBaseHelper(getApplicationContext());
        try {
            db.openDataBase();
        } catch (SQLException e) {
            throw e;
        } finally {
            db.close();
        }
        list = (ListView) findViewById(R.id.basket_list);

        updateAdapter();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setItems(selections, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                String value = "";
                String foodId = "";
                cursor.moveToFirst();
                do {
                    if (cursor.getString(0).equals(((TextView) myView).getText())) {
                        value = cursor.getString(1);
                        foodId = cursor.getString(2);
                        break;
                    }
                } while (cursor.moveToNext());

                switch (item) {
                case 0:
                    Intent intent = new Intent(BasketActivity.this, ProductTabWidgetActivity.class);
                    intent.putExtra("foodId", foodId);
                    ProductTabWidgetActivity.fromScan = false;
                    startActivity(intent);
                    alert.dismiss();
                    break;
                case 1:
                    db.removeItemFromBasket(value);
                    updateAdapter();
                    alert.dismiss();
                    break;
                default:
                    throw new Error("An error occured");
                }
            }
        });
        alert = builder.create();

        list.setTextFilterEnabled(true);
        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                myView = view;
                alert.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.basket_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        Intent i;
        switch (item.getItemId()) {
        case R.id.scan:
            startBarcodeScanner();
            return true;
        case R.id.home:
            i = new Intent(getApplicationContext(), HomescreenActivity.class);
            startActivity(i);
            return true;
        case R.id.settings:
            i = new Intent(getApplicationContext(), UserInfoActivity.class);
            startActivity(i);
            return true;
        case R.id.quit:
            moveTaskToBack(true);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private void updateAdapter() {
        try {
            date = getIntent().getExtras().get("date").toString();
        } catch (Exception e) {
            date = DateHelper.getDate();
        }

        RelativeLayout rel = (RelativeLayout) findViewById(R.id.relLayoutBasket);
        TextView img = (TextView) ((ViewGroup) rel).getChildAt(0);
        TextView txt = (TextView) ((ViewGroup) rel).getChildAt(1);

        cursor = db.getItemsInBasket(date);
        items.clear();

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                items.add(cursor.getString(0));
            }
            int score = getShoppingBasketRatingFromDate(date);
            img.setBackgroundDrawable(getResources().getDrawable(ColorHelper.getColor(score)));

            txt.setText(Integer.toString(score));
        } else {
            Toast.makeText(getApplicationContext(), "Din indkøbskurv er tom", Toast.LENGTH_LONG)
                            .show();
            img.setBackgroundDrawable(null);
            txt.setText("");
        }

        list.setAdapter(new ArrayAdapter<String>(this, R.layout.basket_list, items));
    }

    private void startBarcodeScanner() {
        Intent i = new Intent(getApplicationContext(), CaptureActivity.class);
        startActivity(i);
    }

    public int getShoppingBasketRatingFromDate(String date) {
        float fat = 0f;
        float saturatedFat = 0f;
        float monoUnsaturatedFat = 0f;
        float polyUnsaturatedFat = 0f;
        float protein = 0f;
        float carbonHydrate = 0f;
        float sugar = 0f;
        float alcohol = 0f;
        float ash = 0f;
        float water = 0f;

        Cursor cursor = db.getNutrientsFromFoodIdForRating(date);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                int compId = Integer.parseInt(cursor.getString(0));
                switch (compId) {
                case 1:
                    protein += Float.parseFloat(cursor.getString(1));
                    break;
                case 3:
                    fat += Float.parseFloat(cursor.getString(1));
                    break;
                case 4:
                    saturatedFat += Float.parseFloat(cursor.getString(1));
                    break;
                case 5:
                    monoUnsaturatedFat += Float.parseFloat(cursor.getString(1));
                    break;
                case 6:
                    polyUnsaturatedFat += Float.parseFloat(cursor.getString(1));
                    break;
                case 8:
                    carbonHydrate += Float.parseFloat(cursor.getString(1));
                    break;
                case 9:
                    sugar += Float.parseFloat(cursor.getString(1));
                    break;
                case 11:
                    alcohol += Float.parseFloat(cursor.getString(1));
                    break;
                case 12:
                    ash += Float.parseFloat(cursor.getString(1));
                    break;
                case 13:
                    water += Float.parseFloat(cursor.getString(1));
                    break;
                default:
                    break;
                }
            }
        }
        
        float total = fat + protein + carbonHydrate + alcohol + ash + water;
        
        fat = fat / total * 100;
        saturatedFat = saturatedFat / total * 100;
        monoUnsaturatedFat = monoUnsaturatedFat / total * 100;
        polyUnsaturatedFat = polyUnsaturatedFat / total * 100;
        protein = protein / total * 100;
        carbonHydrate = carbonHydrate / total * 100;
        sugar = sugar / total * 100;
        
        return FoodRating.calculateRating(fat, saturatedFat, monoUnsaturatedFat,
                        polyUnsaturatedFat, protein, carbonHydrate, sugar);
    }
}
